package component;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;

public class CustomJTable extends JTable {
    
    public CustomJTable(String[] columnNames) {

        setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

        setRowHeight(40);
        
        //重写默认TableModel，使格子无法选择修改
        DefaultTableModel tableModel = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        //设置TableModel
        setModel(tableModel);

        //添加各列
        for (String columnName : columnNames){
            tableModel.addColumn(columnName);
        }
        //给每一列设置tableCellRenderer
        DefaultTableCellRenderer tableCellRenderer = new DefaultTableCellRenderer();
        tableCellRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        for (int n = 0; n < tableModel.getColumnCount(); n++) {
            getColumnModel().getColumn(n).setCellRenderer(tableCellRenderer);
        }

        for (int column = 0; column < getColumnCount(); column++) {
            TableColumn tableColumn = getColumnModel().getColumn(column);
            int preferredWidth = tableColumn.getMinWidth();
            int maxWidth = tableColumn.getMaxWidth();

            for (int row = 0; row < getRowCount(); row++) {
                TableCellRenderer cellRenderer = getCellRenderer(row, column);
                Component c = prepareRenderer(cellRenderer, row, column);
                int width = c.getPreferredSize().width + getIntercellSpacing().width;
                preferredWidth = Math.max(preferredWidth, width);

                //  We've exceeded the maximum width, no need to check other rows

                if (preferredWidth >= maxWidth) {
                    preferredWidth = maxWidth;
                    break;
                }
            }

            tableColumn.setPreferredWidth(preferredWidth);
        }

    }

    public static void resizeColumnWidth(JTable table) {

        final TableColumnModel columnModel = table.getColumnModel();
        for (int column = 0; column < table.getColumnCount(); column++) {
            int width = 15; // Min width
            for (int row = 0; row < table.getRowCount(); row++) {
                TableCellRenderer renderer = table.getCellRenderer(row, column);
                Component comp = table.prepareRenderer(renderer, row, column);
                width = Math.max(comp.getPreferredSize().width +1 , width);
            }
            if(width > 300)
                width=300;
            columnModel.getColumn(column).setPreferredWidth(width);
        }
    }
    
}
